package com.xl.sharedModel;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import java.util.Random;

/**
 * JdkVersion: 1.8
 * Author: lei·xie
 * Created: 2024/8/7 0007 10:44
 * Description: 共享模型 转账问题
 */
@Slf4j(topic = "c.Test7")
public class Test07 {

    public static void main(String[] args) throws InterruptedException {
        Account accountA = new Account(1000);
        Account accountB = new Account(1000);
        Thread t1 = new Thread(()->{
            for (int i = 0; i < 1000; i++) {
                accountA.transfer(accountB, randomAmount());
            }
        },"t1");
        Thread t2 = new Thread(()->{
            for (int i = 0; i < 1000; i++) {
                accountB.transfer(accountA, randomAmount());
            }
        },"t2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        //查看转账2000次后的总金额
        log.debug("total: {}",(accountA.getMoney()+accountB.getMoney()));
    }

    //Random为线程安全 随机1-5
    public static int randomAmount() {
        return new Random().nextInt(100)+1;
    }
}

@Getter
@Setter
class Account {
    private int money;
    public Account(int money) {
        this.money = money;
    }

    //转账
    public void transfer(Account target, int amount) {
        synchronized (Account.class) {
            if (this.money >= amount) {
                this.setMoney(this.getMoney()-amount);
                target.setMoney(target.getMoney()+amount);
            }
        }
    }
}
